package ddd.ajava.chapter2.question10;

import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;

import ddd.ajava.util.StringUtil;

/**
 * @author lenovo
 * 反射生成SQL的insert语句
 * 为任向对象生成对应的Insert语句
 * insert into person (name,age,sex,ismarried ) values(‘洋洋’,5,’male’,false)
 * 1.反射获取类名
 * 2.获取属性名
 * 3.通过get获取变量值
 */
public class GenerateSQL {
	
	public static void main(String[] args) {
		GenerateSQL gSQL=new GenerateSQL();
		Person person=new Person();
		person.setName("洋洋");
		person.setAge(5);
		person.setSex("Male");
		person.setIsMerried(false);
		String insert=gSQL.generateInsert(person);
		System.out.println("Generate SQL:"+insert);
	}
	
	public String generateInsert(Object entity){
		StringBuilder sb=new StringBuilder();
		StringBuilder sbValue=new StringBuilder();
		Class clazz=entity.getClass();
		//反射获取类名
		String className=clazz.getSimpleName();
		sb.append("insert into "+className+" (");
		sbValue.append("values(");
		//获取属性名
		Field[] fields=clazz.getDeclaredFields();
		for(Field f:fields){
			sb.append(f.getName().toLowerCase()+",");
			//通过get获取变量值
			String type=f.getType().getCanonicalName();
			//String类型的加单引号
			String methodName="get"+StringUtil.firstCharToUpper(f.getName());
			Object fieldValue=null;
			try {
				Method method=clazz.getMethod(methodName);
				fieldValue=method.invoke(entity);
			} catch (SecurityException e) {
				e.printStackTrace();
			} catch (NoSuchMethodException e) {
				e.printStackTrace();
			} catch (IllegalArgumentException e) {
				e.printStackTrace();
			} catch (IllegalAccessException e) {
				e.printStackTrace();
			} catch (InvocationTargetException e) {
				e.printStackTrace();
			}
			if(type.equals("java.lang.String")){
				sbValue.append("'"+fieldValue.toString()+"',");
			}else{
				sbValue.append(fieldValue.toString()+",");
			}
		}
		StringBuilder generateString=new StringBuilder();
		generateString.append(sb.substring(0, sb.length()-1)+" ) ");
		generateString.append(sbValue.substring(0, sbValue.length()-1)+") ");
		return generateString.toString();
	}
}
